<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑药品' : '新增药品' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="药品编码" prop="drugCode">
              <el-input 
                v-model="form.drugCode" 
                placeholder="请输入药品编码" 
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="药品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入药品名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="西药" value="西药" />
                <el-option label="中药" value="中药" />
                <el-option label="中成药" value="中成药" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="剂型" prop="dosageForm">
              <el-select v-model="form.dosageForm" placeholder="请选择剂型" style="width: 100%">
                <el-option label="片剂" value="片剂" />
                <el-option label="胶囊" value="胶囊" />
                <el-option label="口服液" value="口服液" />
                <el-option label="注射剂" value="注射剂" />
                <el-option label="软膏" value="软膏" />
                <el-option label="滴眼液" value="滴眼液" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="启用" />
                <el-option label="禁用" value="禁用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">价格与库存</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="price">
              <el-input-number 
                v-model="form.price" 
                :precision="2" 
                :step="0.1" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="预警数量" prop="alertQuantity">
              <el-input-number 
                v-model="form.alertQuantity" 
                :min="0" 
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">厂家信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="批准文号" prop="approvalNumber">
              <el-input v-model="form.approvalNumber" placeholder="请输入批准文号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">处方信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否处方药">
              <el-switch 
                v-model="form.properties.isPrescription" 
                active-text="是" 
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="是否管制药品">
              <el-switch 
                v-model="form.properties.isControlled" 
                active-text="是" 
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="存储条件" prop="properties.storageCondition">
              <el-input 
                v-model="form.properties.storageCondition" 
                placeholder="请输入存储条件"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">用法用量</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="用量" prop="usage.dosage">
              <el-input v-model="form.usage.dosage" placeholder="请输入用量" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="频次" prop="usage.frequency">
              <el-input v-model="form.usage.frequency" placeholder="请输入频次" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="用药途径" prop="usage.route">
              <el-input v-model="form.usage.route" placeholder="请输入用药途径" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">适应症和禁忌症</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="适应症" prop="indications">
              <el-select
                v-model="form.indications"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入适应症"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="禁忌症" prop="contraindications">
              <el-select
                v-model="form.contraindications"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入禁忌症"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="不良反应" prop="sideEffects">
              <el-select
                v-model="form.sideEffects"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入不良反应"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { drugAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const drugId = ref(route.params.id)
const isEdit = computed(() => !!drugId.value)

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 表单数据
const form = reactive({
  drugCode: '',
  name: '',
  genericName: '',
  category: '西药', // 默认选择西药，符合后端验证要求
  specification: '',
  dosageForm: '',
  manufacturer: '',
  approvalNumber: '',
  price: 0,
  properties: {
    isPrescription: false,
    isControlled: false,
    storageCondition: ''
  },
  usage: {
    dosage: '',
    frequency: '',
    route: ''
  },
  indications: [],
  contraindications: [],
  sideEffects: [],
  alertQuantity: 50,
  status: '启用'
})

// 表单验证规则
const rules = {
  drugCode: [
    { required: true, message: '请输入药品编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{2,20}$/, message: '药品编码只能包含字母和数字，长度为2-20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入药品名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择药品分类', trigger: 'change' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  dosageForm: [
    { required: true, message: '请选择剂型', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取药品详情
const fetchDrugDetail = async () => {
  if (!drugId.value) return
  
  loading.value = true
  try {
    console.log('获取药品详情, ID:', drugId.value)
    const res = await drugAPI.getDrug(drugId.value)
    console.log('药品详情响应:', res)
    
    if (res.success && res.data) {
      console.log('设置药品数据:', res.data)
      const drugData = res.data
      
      // 重置表单，确保所有字段都有默认值
      Object.keys(form).forEach(key => {
        if (typeof form[key] === 'string') form[key] = ''
        else if (typeof form[key] === 'number') form[key] = 0
        else if (Array.isArray(form[key])) form[key] = []
      })
      
      // 重置嵌套对象
      form.properties = {
        isPrescription: false,
        isControlled: false,
        storageCondition: ''
      }
      
      form.usage = {
        dosage: '',
        frequency: '',
        route: ''
      }
      
      // 设置基本字段
      form.drugCode = drugData.drugCode || ''
      form.name = drugData.name || ''
      form.genericName = drugData.genericName || ''
      form.category = drugData.category || ''
      form.specification = drugData.specification || ''
      form.dosageForm = drugData.dosageForm || ''
      form.manufacturer = drugData.manufacturer || ''
      form.approvalNumber = drugData.approvalNumber || ''
      form.price = drugData.price || 0
      form.alertQuantity = drugData.alertQuantity || 50
      form.status = drugData.status || '启用'
      
      // 处理嵌套对象
      if (drugData.properties) {
        form.properties.isPrescription = drugData.properties.isPrescription || false
        form.properties.isControlled = drugData.properties.isControlled || false
        form.properties.storageCondition = drugData.properties.storageCondition || ''
      }
      
      if (drugData.usage) {
        form.usage.dosage = drugData.usage.dosage || ''
        form.usage.frequency = drugData.usage.frequency || ''
        form.usage.route = drugData.usage.route || ''
      }
      
      // 处理数组
      form.indications = Array.isArray(drugData.indications) ? [...drugData.indications] : []
      form.contraindications = Array.isArray(drugData.contraindications) ? [...drugData.contraindications] : []
      form.sideEffects = Array.isArray(drugData.sideEffects) ? [...drugData.sideEffects] : []
      
      console.log('表单数据设置完成:', form)
    } else {
      console.error('获取药品详情失败:', res)
      ElMessage.error('获取药品详情失败: ' + (res.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取药品详情异常:', error)
    ElMessage.error('获取药品详情失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 准备提交的数据 - 深拷贝避免响应式对象问题
      const drugData = JSON.parse(JSON.stringify(form))
      
      // 检查并处理可能的数据格式问题
      // 1. 确保所有必要字段存在（仅在新增时检查drugCode）
      if (!isEdit.value && !drugData.drugCode) {
        throw new Error('药品编码不能为空')
      }
      
      // 2. 确保category字段符合后端要求
      if (!['西药', '中成药', '中药饮片', '生物制品'].includes(drugData.category)) {
        drugData.category = '西药'
      }
      
      // 3. 确保status字段符合后端要求
      if (!['启用', '禁用'].includes(drugData.status)) {
        drugData.status = '启用'
      }
      
      // 4. 确保嵌套对象格式正确
      if (!drugData.properties) {
        drugData.properties = {
          isPrescription: false,
          isControlled: false,
          storageCondition: ''
        }
      }
      
      if (!drugData.usage) {
        drugData.usage = {
          dosage: '',
          frequency: '',
          route: ''
        }
      }
      
      // 5. 确保数组字段格式正确
      if (!Array.isArray(drugData.indications)) drugData.indications = []
      if (!Array.isArray(drugData.contraindications)) drugData.contraindications = []
      if (!Array.isArray(drugData.sideEffects)) drugData.sideEffects = []
      
      // 6. 转换数值字段
      drugData.price = Number(drugData.price) || 0
      drugData.alertQuantity = Number(drugData.alertQuantity) || 50
      
      // 7. 移除可能导致问题的字段
      if (drugData.inventory) delete drugData.inventory
      if (drugData.createdAt) delete drugData.createdAt
      if (drugData.updatedAt) delete drugData.updatedAt
      if (drugData.id) delete drugData.id
      if (drugData._id) delete drugData._id
      
      // 8. 如果是编辑模式，移除drugCode字段（不允许更新）
      if (isEdit.value) {
        delete drugData.drugCode
      }
      
      console.log('提交药品数据:', drugData)
      
      let res
      if (isEdit.value) {
        console.log(`更新药品ID: ${drugId.value}`)
        res = await drugAPI.updateDrug(drugId.value, drugData)
      } else {
        res = await drugAPI.createDrug(drugData)
      }
      
      console.log('提交药品响应:', res)
      
      if (res && (res.success || res.status === 200)) {
        ElMessage.success(isEdit.value ? '药品更新成功' : '药品创建成功')
        goBack()
      } else {
        ElMessage.error(res?.message || (isEdit.value ? '药品更新失败' : '药品创建失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '药品更新失败' : '药品创建失败', error)
      if (error.response && error.response.data) {
        console.error('错误详情:', error.response.data)
        ElMessage.error(`${isEdit.value ? '药品更新失败' : '药品创建失败'}: ${error.response.data.message || error.message}`)
      } else {
        ElMessage.error(isEdit.value ? '药品更新失败' : '药品创建失败')
      }
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  if (isEdit.value) {
    fetchDrugDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}
</style> 